import worker, { MessageEvents, ErrorEvent } from '@ohos.worker';
import fs from '@ohos.file.fs'
import { MediaItem, WifiDeviceManager } from '@ohos/common';

// 创建worker线程中与主线程通信的对象
const workerPort = worker.workerPort

// worker线程接收主线程信息
workerPort.onmessage = (e: MessageEvents): void => {
  // data：主线程发送的信息
  let data: ArrayBuffer = e.data
  let length = data.byteLength
  console.log("worker.ets onmessage:"+data.byteLength);
  let offset: number = 0
  while (offset < length) {
    // WifiDeviceManager.getInstance().sendToServer(data.slice(offset, offset + 1024))
    workerPort.postMessage(data.slice(offset, offset + 1024))
    offset = offset + 1024
    if(offset >= length) {
      AppStorage.setOrCreate('receivedState', 6)
      // workerPort.postMessage('传输结束')
    }
  }
  // while (option.offset < FileAsset.size) {
  //   try {
  //     let data: ArrayBuffer = new ArrayBuffer(1024 * 1)
  //     let length: number = fs.readSync(file.fd, data, option);
  //     if (length > 0) {
  //       console.info(`read file data succeed: offset=${option.offset} length=${length},`);
  //       // await this.sendToServer(data)
  //       WifiDeviceManager.getInstance().sendToServer(data)
  //       option.offset = option.offset + length
  //     }
  //     if(option.offset >= FileAsset.size) {
  //       fs.close(file.fd)
  //       AppStorage.setOrCreate('receivedState', 6)
  //       // worker线程向主线程发送信息
  //       workerPort.postMessage('传输结束')
  //     }
  //   }
  //   catch (err) {
  //     console.error("read file data failed:"+JSON.stringify(err));
  //   }
  // }
}

// worker线程发生error的回调
workerPort.onerror = (err: ErrorEvent) => {
  console.log("worker.ets onerror" + err.message);
}